import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import {VueJsonp} from 'vue-jsonp'

import { getuserinfo } from '../api/user.js'

const store = new Vuex.Store({
	state: {
		loginstatus: false,
		statusHight: uni.getSystemInfoSync().statusBarHeight, // 手机状态栏高度
		screenHeight: uni.getSystemInfoSync().screenHeight, // 手机屏幕高度
		windowHeight: uni.getSystemInfoSync().windowHeight, // 手机窗口高度
		userinfo: {
			userId: 13,
			hesdPortrait: ''
		},
		Usernum: {
		},
		address: {
			latitude: '',
			longitude: '',
			city: ''
		},
		locationCity: ''
	},
	mutations: {
		// 设置用户登录消息
		setInfo (state, params) {
		   state.userinfo = params
		},
		// 设置当前定位城市
		setLocationCity (state, city) {
			state.locationCity = city
		},
		// 设置用户数值
		setUserNum (state, num) {
			state.Usernum = num
		},
		// 修改登录状态
		setStatus (state, status) {
			state.loginstatus = status
		},
		// 设置经纬度
		setAdress (state, params) {
			state.address = params
		}
	},
	actions: {
		// 异步获取用户信息
		async getUserInfo ({commit, state}, userId) {
			const res = await getuserinfo({userId: userId || state.userinfo.userId})
			const { data, ...count} = res.data.data
			uni.setStorageSync('uerinfo', data)
			uni.setStorageSync('userCount', count)
			commit('setStatus', true)
			commit('setInfo', data)
			commit('setUserNum', count)
		},
		// 异步获取城市地点
		async getCity ({commit, state}, that) {
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					let url = `https://apis.map.qq.com/ws/geocoder/v1/?key=AZABZ-UFQAJ-C4YF2-KE2IY-WOU42-3VBOQ&location=${res.latitude},${res.longitude}&output=jsonp`
						that.$jsonp(url)
							.then(result => {
							const params = {
								longitude: res.longitude || '',
								latitude:res.latitude || '',
								address: result.result.address
							}
							commit('setAdress',params )
							commit('setLocationCity', result.result.ad_info.city )
							})
							.catch(err => {
							uni.showToast({
								title: '获取位置失败'
							   })
							})
				},
				fail: (err) => {
					uni.showToast({
						title: '获取地理位置失败'
					})
				}
			})
		}
	}
})

export default store
